from django.shortcuts import render
from datetime import datetime
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from student import models
# Create your views here.

# 学生登录
def studentLogin(request):
    if request.method=='Get':
        return render(request,'login.html')
    elif request.method == 'POST':
        response = {'msg':'','status':False}
        # 获取表单信息
        student_id = request.POST.get('student_id')
        password = request.POST.get('password')

        # 通过学号获取该学生实体
        student = models.Student.objects.get(student_id=student_id)

        if password == student.password:  # 登录成功
            request.session['username']=student_id    #user的值发送给session里的username
            request.session['is_login']=True   #认证为真
            response['status'] = True
            # 渲染index模板
            return render(request, 'index.html')
        else:
            return render(request,'login.html',{ 'message':'密码不正确' })
    elif request.method == 'GET':
        return render(request, 'login.html')
    else:
        return HttpResponse("请使用GET或POST请求数据")


#学生退出登录
def stuLogout(request):
    # logout(request)
    request.session.clear()
    url = reverse('index')
    return redirect(url)

def userfile(request):
    if request.session.get('is_login',None):  #若session认证为真
        username = request.session.get('username',None)
        student = models.Student.objects.get(student_id=username)
        return render(request, 'userfile.html',{'student': student})

# 注册
from django import forms

class studentModelform(forms.ModelForm):
    class Meta:
        model = models.Student
        fields=["student_id","password","student_name","password","sex","academy","major","student_Class","email"]

def studentRegister(request):
    """注册"""
    if request.method == "GET":
        form = studentModelform()
        return render(request, 'register.html',{"form" : form})
    # 用户通过POST提交数据，数据校验。
    form = studentModelform(data=request.POST)
    #如果数据合法，保存到数据库
    if form.is_valid():
        form.save()
        return render(request,'index.html')
    # 校验失败
    else:
        return render(request, 'register.html', {"form" : form})
